package com.example.chattingroom.api;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


@Component
public class TestWebSocketAPI extends TextWebSocketHandler {
    //websocket连接成功后自动被调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session)throws Exception
    {
        System.out.println("TestAPI连接成功");
    }

    //session通过获取websocket连接，记录对话双方的信息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //这个方法是在websocket收到信息的时候被自动调用的
        System.out.println("TestAPI收到信息！"+message.toString());

        //session是个会话，记录了对话双方的信息（session持有了websocket的通信连接）
        session.sendMessage(message);
    }

    //websocket出现异常时被自动调用
    @Override
    public void handleTransportError(WebSocketSession session,Throwable exception)throws Exception
    {
        System.out.println("TestAPI连接异常！");
    }

    //websocket断开连接被自动调用
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)throws Exception{
        System.out.println("TestAPI断开连接！");
    }
}
